import { defineStore } from 'pinia';
import { ref, watch, nextTick } from 'vue';
import route from '@/router/index'
import { findTree } from '@/utils/tool';

export const useLayout = defineStore('layout', () => {
  const collapsed = ref(false)
  
  const switchCollapsed = () => {
    collapsed.value = !collapsed.value
  }

  return {
    collapsed,
    switchCollapsed
  }
})

export const useMenu = defineStore('menu', () => {
  const selectedKeys = ref([]) // 当前选中得菜单
  const historyRouters = ref([]) // 历史菜单
  const getters = {
    currentSubMenu() {
      const sysRouters = localStorage.getItem('menuList') ? JSON.parse(localStorage.getItem('menuList')) : []
      const currentRouters = findTree(sysRouters, selectedKeys.value[0])
      return currentRouters
    },
    openSubmenuKeys() {
      const sysRouters = localStorage.getItem('menuList') ? JSON.parse(localStorage.getItem('menuList')) : []
      const currentRouters = findTree(sysRouters, selectedKeys.value[0])
      return currentRouters.map(e => e.id)
    }
  }
  
  const menuClick = (e) => {
    route.push(e.item.path)
  }
  const updataSelectedKeys = (key) => {
    selectedKeys.value = [key]
  }
  return {
    selectedKeys,
    historyRouters,
    menuClick,
    updataSelectedKeys,
    getters
  }
})

export const useTheme = defineStore('theme', () => {
  // 模式 default默认、，dark暗黑模式，light高亮
  const mode = ref(localStorage.getItem('oaTheme') || 'default')
  nextTick(() => {
    document.getElementsByTagName('body')[0].style.setProperty('--container-bg', mode.value === 'dark' ? '#1d1d1d' : '#fff')
    document.getElementsByTagName('body')[0].style.setProperty('--container-shadow', mode.value === 'dark' ? '#404142' : '#e2e5ed')
  })
  watch(()=> mode.value, (val) => {
    nextTick(() => {
      document.getElementsByTagName('body')[0].style.setProperty('--container-bg', mode.value === 'dark' ? '#1d1d1d' : '#fff')
      document.getElementsByTagName('body')[0].style.setProperty('--container-shadow', mode.value === 'dark' ? '#404142' : '#e2e5ed')
    })
    localStorage.setItem('oaTheme', val)
  })
  return {
    mode
  }
}) 